import React, { Component } from 'react';
import { Button, message, List, Icon, Popconfirm } from 'antd';
import dayjs from 'dayjs';
import axios from 'axios';
import ArticleModal from './modal';
import CommentModal from './commentModal'
import eventEmitter from '../utils/utils.js';
import './index.css';

const IconText = ({ type, text, onClick }) => (
  <span onClick={onClick && onClick}>
    <Icon type={type} style={{ marginRight: 8 }} />
    {text}
  </span>
);
export default class Article extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      current: 1,
      pageSize: 10,
      total: 0,
    }
  }
  loadArticleList = (current = 1) => {
    // 获取文章表
    const res = axios.get(`http://localhost:8000/article/get?currentPage=${current}`);
    // 这里的res服务端返回的是Promise对象
    Promise.resolve(res).then((rtn) => {
      const data = rtn.data || {};
      const lists = data.lists || [];
      lists.forEach(item => {
        item.createTime = dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss');
      });
      this.setState({
        dataSource: lists,
        total: data.total,
        pageSize: data.pageSize,
        current: data.current,
      })
    })
  }
  componentDidMount() {
    this.loadArticleList();
    eventEmitter.on('addArticle', (params) => {
      // 新增回到首页，编辑回到当前页
      const current =  params ? this.state.current : 1;
      this.loadArticleList(current);
    })
    eventEmitter.on('addComment', () => {
      this.loadArticleList(this.state.current);
    })
  }
  addArticle = () => {
    // 添加文章
    this.articleModal.show();
  }
  pageChange = (current) => {
    // 点击分页
    this.loadArticleList(current);
  }
  handleEdit = (records) => {
    // 编辑操作
    this.articleModal.show(records);
  }
  handleDelete = (records) => {
    // 删除操作
    const { current } = this.state;
    const res = axios.delete(`http://localhost:8000/article/delete/${records._id}`);
    Promise.resolve(res).then((rtn) => {
      const data = rtn.data || {};
      if (data && data.success) {
        message.success(data.msg);
        this.loadArticleList(current);
      }
    })
  }
  handleStarPraise = (records, type) => {
    const { current } = this.state;
    const url = type === 'star' ? `http://localhost:8000/article/star/${records._id}` : `http://localhost:8000/article/praise/${records._id}`;
    axios.put(url).then(res => {
      const data = res.data || {};
      if (data && data.success) {
        message.success(data.msg);
        this.loadArticleList(current);
      }
    })
  }
  handleComment = (records) => {
    this.commentModal.show(records);
  }
  render() {
    const { dataSource, total, pageSize, current } = this.state;
    
    return (
     <div>
      <Button type="primary" icon="plus"className="add-article-btn" onClick={this.addArticle}>新增</Button>
      <List
        itemLayout="vertical"
        size="large"
        pagination={{
          pageSize,
          total,
          current,
          onChange: this.pageChange
        }}
        dataSource={dataSource}
        renderItem={item => (
          <List.Item
            key={item._id}
            actions={[
              <IconText type="star-o" text={item.stars} onClick={this.handleStarPraise.bind(this, item, 'star')}/>, 
              <IconText type="like-o" text={item.praise} onClick={this.handleStarPraise.bind(this, item, 'praise')} />, 
              <IconText type="message" onClick={this.handleComment.bind(this, item)} />,
              <IconText type="edit" text="" onClick={this.handleEdit.bind(this, item)} />,
              <Popconfirm onConfirm={this.handleDelete.bind(this, item)} title="确定删除？" okText="确定" cancelText="删除">
                <IconText type="delete" text=""/>
              </Popconfirm>
            ]}
            extra={<img width={272} alt="logo" src={item.articleImg[0] && item.articleImg[0].url} />}
          >
            <List.Item.Meta
              title={item.title}
              description={item.desc}
            />
            {item.content}
            <p style={{marginTop: 10, color: 'skyBlue'}}><small>发布时间：{dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')}</small></p>
          </List.Item>
        )}
      />
      <ArticleModal ref={r => this.articleModal = r} />
      <CommentModal ref={r => this.commentModal = r} />
     </div>
    )
  }
}
